package com.foxit.pdf2pdf.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.json.JSONException;
import org.json.JSONObject;

@Controller
public class TranslateController {
	protected static final Logger logger = Logger.getLogger(TranslateController.class);
	
	private static String supportLanguage = "http://it-translate.foxitcloud.com/api/support_language";
	private static String detectLanguage = "http://it-translate.foxitcloud.com/api/detect_language";
	private static String translateText = "http://it-translate.foxitcloud.com/api/translate_text";
	private static String webTranslage = "https://it-translate.foxitcloud.com";
	private static String success = "success";
	private static String sourcetxt = "source_text"; 
	private static String language = "language";
	private static String languages = "languages";
	private static String languagecout = "language_cout";
	private static String target = "target";
	private static String ret = "ret";
	private static String source = "source";
	private static String translatedtxt = "translated_text";
	private HttpServletRequest servletRequest = null;
	public static String getLanguages() {
		return languages;
	}
	public static String getLanguagecout() {
		return languagecout;
	}
	public static String getTranslatedtxt() {
		return translatedtxt;
	}

	public static String getSource() {
		return source;
	}
	public static String getSupportLanguage() {
		return supportLanguage;
	}

	public static String getDetectLanguage() {
		return detectLanguage;
	}

	public static String getTranslateText() {
		return translateText;
	}

	public static String getWebTranslage() {
		return webTranslage;
	}

	public static String getSuccess() {
		return success;
	}

	public static String getSourcetxt() {
		return sourcetxt;
	}

	public static String getLanguage() {
		return language;
	}

	public static String getTarget() {
		return target;
	}

	public static String getRet() {
		return ret;
	}
	
	/**
	 * 
	 * @Description:查看支持语言
	 * @param request
	 * @param response
	 * @return
	 * @author: huangwb 
	 * @throws JSONException 
	 * @throws IOException 
	 * @date: 2014年8月7日 下午1:25:39
	 * @throws:
	 */
	@RequestMapping(value = "/supportLanguage.do")
	public String GetSupportLanguage(HttpServletRequest request,HttpServletResponse response) throws JSONException, IOException{
		JSONObject res = new JSONObject();
		try {
			JSONObject json = new JSONObject();
			json.put(getTarget(), "en");//获取name
			String str = sendPost(getSupportLanguage(), json);
			JSONObject ret = new JSONObject(str);
			int flag = (Integer)ret.get(getRet());
			
			if(flag == 0){
				res.put(getSuccess(), true);
				res.put(getLanguagecout(), ret.get(getLanguagecout()));
				res.put(getLanguages(), ret.get(getLanguages()));
			}else{
				res.put(getSuccess(), false);
			}
			response.getWriter().write(res.toString());
		} catch (Exception e) {
			logger.error(e.getMessage());
			res.put(getSuccess(), false);
			response.getWriter().write(res.toString());
		}
		
		return null;
	}
	/**
	 * 
	 * @Description:语言检测
	 * @param request
	 * @param response
	 * @return
	 * @author: huangwb 
	 * @date: 2014年8月7日 下午1:25:22
	 * @throws:
	 */
	@RequestMapping(value = "/detectLanguage.do")
	public String GetDetectLanguage(HttpServletRequest request,HttpServletResponse response){
		try {
			JSONObject res = new JSONObject();
			String txt = "";
			JSONObject json = new JSONObject();
			json.put(getSourcetxt(), txt);
			String str = sendPost(getDetectLanguage(), json);
			JSONObject ret = new JSONObject(str);
			int flag = (Integer)ret.get(getRet());
			
			if(flag == 0){
				String language = ret.getString(getLanguage());
				res.put(getSuccess(), true);
				res.put(getLanguage(), language);
			}else{
				res.put(getSuccess(), false);
			}
			
			response.getWriter().write(res.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return null;
	}
	
	/**
	 * @Description:翻译
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @author: huangwb
	 * @date: 2014年8月7日 下午1:25:13
	 * @throws:
	 */
	@RequestMapping(value = "/translateText.do")
	public String GetTranslateText(HttpServletRequest request,HttpServletResponse response) throws IOException{
//		String resp = null;
//		String target = request.getParameter(getTarget());
//		HttpSession session = request.getSession();
//		ServletContext  application  = session.getServletContext();    
//		String serverRealPath = application.getRealPath("/") ;
//		logger.error("1 serverRealPath=" + serverRealPath);
//		serverRealPath = serverRealPath.substring(0, serverRealPath.length() - 2);
//		logger.error("2 serverRealPath=" + serverRealPath);
//		String fileName = request.getParameter("fileName");
//		String filePath = serverRealPath + fileName;
//		
//		String newfilename = filePath.substring(0,filePath.length() - 4) + "new.pdf";
//		logger.error("newfilename=" + newfilename);
//		logger.error("Start translating....");
//		try{
//			Conver2PDFTask task = new Conver2PDFTask(filePath, null);
//			
//			long mgr = task.StartProcess();
//
//			if(mgr != -1){
//				Map<Integer, Integer> page = task.GetPage();
//				
//				logger.error("GetContent...");
//				for(Integer index : page.keySet()){
//					int paragraph = page.get(index);
//					String txt = null;
//					for(int i = 0;i < paragraph;i++){
//						logger.error("pageindex=" + index + "," + "paragraphindex=" + i);
//						String content = task.GetContent(index, i);
//						JSONObject json = new JSONObject();
//						json.put(getTarget(), target);
//						json.put(getSourcetxt(), content);
//						String getStr = sendPost(getTranslateText(), json);
//						logger.error("sendPost=" + getStr);
//						JSONObject getJson = new JSONObject(getStr);
//						int isRet = (Integer)getJson.get(getRet());
//						logger.error("ret=" + isRet);
//						if(isRet == 0){
//							logger.error("ret == 0");
//							txt = getJson.getString(getTranslatedtxt());
//						}else{
//							logger.error("ret == 1000");
//							txt = tryTranslate(json);
//							
//							if(txt == null){
//								txt = content;
//							}
//						}
//						logger.error("txt == " + txt);
//						task.AddContent(index, i, txt);
//					}
//				}
//				
//				boolean closeFlag = task.CloseTranslate(mgr,newfilename);
//				
//				if(!closeFlag){
//					logger.error("dll can not close");
//					resp = GetResMap(false, "Translate Error!");
//					response.getWriter().write(resp);
//					return null;
//				}
//			}else{
//				logger.error("dll can not start");
//				resp = GetResMap(false, "Translate Error!");
//				response.getWriter().write(resp);
//				return null;
//			}
//
//		}catch(Exception ex){
//			logger.error(ex.getMessage());
//			resp = GetResMap(false, "Translate Error!");
//			response.getWriter().write(resp);
//			return null;
//		}
//		String filepath = newfilename.substring(serverRealPath.length());
//		resp = GetResMap(true,filepath);
//		response.getWriter().write(resp);
		return null;
	}
	
	/**
	 * 
	 * @Description:将要转换的map转成json 传给前端
	 * @param flag
	 * @param errorMsg
	 * @return
	 * @author: huangwb 
	 * @date: 2014年8月8日 下午1:05:32
	 * @throws:
	 */
	private String GetResMap(boolean flag,String errorMsg){
		Map<String,Object> resMap = new HashMap<String, Object>();
		resMap.put(getSuccess(), flag);
		resMap.put(getSource(), errorMsg);
		
		JSONObject json = new JSONObject(resMap);
		
		return json.toString();
	}
	/**
	 * 
	 * @Description:重试3次
	 * @param json
	 * @return
	 * @author: huangwb 
	 * @date: 2014年8月7日 下午1:16:35
	 * @throws:
	 */
	private String tryTranslate(JSONObject json){
		int count = 0;
		String ret = null;
		try {
			while(count < 3){
				String str = sendPost(getTranslateText(), json);
				JSONObject obj = new JSONObject(str);
				int res= (Integer)obj.get(getRet());
				
				if(res == 0){
					ret = obj.getString(getTranslatedtxt());
					break;
				}
				count++;
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		return ret;
	}
	
//	public static void main(String[] args) {
//		try {
//			JSONObject json = new JSONObject();
//			json.put(getTarget(), "en");
//			String str = sendPost("https://translate.foxitcloud.com/api/support_language", json);
//			System.out.println(str + "++++++++++++");
//			String path = "/usr/share/tomcat/latest/webapps/PDF2PDF";
//			String filename = "/usr/share/tomcat/latest/webapps/PDF2PDF/WebReaderDocPath/53b07fcd-6f01-4426-8dc6-3c754aea241d/53b07fcd-6f01-4426-8dc6-3c754aea241dnew.pdf";
//			System.out.println(filename.substring(path.length()));
//		} catch (Exception e) {
//			logger.error(e.getMessage());
//		}
//	}
	/**
	 * 
	 * @Description:发送到google api 获取结果
	 * @param url
	 * @param json
	 * @return
	 * @throws IOException
	 * @author: huangwb 
	 * @date: 2014年8月7日 下午1:24:45
	 * @throws:
	 */
	public static String sendPost(String url, JSONObject json) throws IOException {
		logger.error("start sendPost....");
		HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        InputStream in = null;
        ByteArrayOutputStream out = null;
        String resjson = new String();
        try {  
            post.setHeader("Content-Type", "application/json; charset=UTF-8");
            StringEntity se = new StringEntity(json.toString(),HTTP.UTF_8);
            se.setContentType("application/json; charset=UTF-8");
            post.setEntity(se);
            logger.error("post...");
            HttpResponse res = client.execute(post);  
            int code = res.getStatusLine().getStatusCode();
            logger.error("code=" + code);
            if(code == HttpStatus.SC_OK){
            	in = res.getEntity().getContent();
            	out = new ByteArrayOutputStream();
            	byte[] buffer = new byte[1024];
            	int len = 0;
            	while((len = in.read(buffer,0,1024)) != -1){
            		out.write(buffer, 0, len); 
            	}
            	
            	resjson = new String(out.toByteArray(),"UTF-8");
            	 logger.error("translate content=" + resjson);
            }  
        } catch (Exception e) {  
            throw new RuntimeException(e);  
        }finally{
        	if(in != null){
        		in.close();
        	}
        	
        	if(out != null){
        		out.close();
        	}
        }
        return resjson;
	}
}
